import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { storage } from "@/utils/storage"
// import AppEvents from '@/utils/app-events'
// import { useStore } from "vuex";
// const store = useStore();

// 本地环境
// export const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); // 判断是否是手机端
export const isMobile = /phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone/i.test(navigator.userAgent); // 判断是否是手机端
export const isWeChat = navigator.userAgent.toLowerCase().includes('micromessenger'); // 判断是否是微信浏览器
export const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1; // 判断是否是安卓机

export let BASEURL = ""; // 部署环境
export let assetsUrl = ""; // 资源
export let orderPay = ""; // 测试支付
export let AI_HOST = "https://www.aia.baidufoundation.org.cn/"; // AI助手

const devHosts = [['//127.0.0.1', '//localhost'], ['//uopen.info.bit.edu.cn']];
const env = getWorkEnv(devHosts); // local dev pro
// const env = 'pro'

function getWorkEnv(hosts: any) {
  let _isDev = 'pro';
  const $herf = window.location.href;
  hosts.forEach((item: any, index: number) => {
    item.forEach(function (host: any) {
      if (index == 0) {
        if ($herf.indexOf(host) !== -1) {
            _isDev = 'local';
        }
      } else {
        if ($herf.indexOf(host) !== -1) {
          _isDev = 'dev';
        }
      }
    });
  })
  return _isDev;
}

let protocol = location.protocol
// let host_url = window.location.protocol + "//" + window.location.hostname;

if (env === "local") {
	// assetsUrl = "../../../src/assets";
	assetsUrl = "./assets";
  // BASEURL = protocol + "//pay.baidufoundation.org.cn"
  BASEURL = protocol + "//useropen.info.bit.edu.cn";
  // BASEURL = "";
  orderPay = "http://pay.baidufoundation.org.cn"
} else if (env === "dev") {
	assetsUrl = "./assets";
  BASEURL = protocol + "//useropen.info.bit.edu.cn";
} else if (env === "pro") {
	assetsUrl = "./assets";
  // BASEURL = protocol + "//biz.oer.baidufoundation.org.cn";
  // BASEURL = host_url + '/api/biz';
  BASEURL = '/api/biz';
}

// 创建 axios 实例
const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASE_API,
  baseURL: BASEURL,
  timeout: 5000,
  headers: { 
    Authorization: "Bearer " + (storage.get('token') || ''),
    "Xdomain-Client": "web_user",
  },
});
// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // console.log(storage.get('token'), config.headers)
    // if (config.url?.indexOf('/v1/payment/target') !== -1) {
    //   config.baseURL = orderPay
    // }
    // token = storage.get('token') || '';
    // if (!token) {
      config.headers['Authorization'] = "Bearer " + (storage.get('token') || '');
    // }
    // config.headers['Content-Type'] = "application/x-www-form-urlencoded"
    // console.log(storage.get('token'))
    // console.log(config)
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message } = response.data;
    // console.log('响应拦截器', response.data);
    if (code === 0) {
      return response;
    } else if ( code == 11101113 ){
      // ElMessage.error(message)
      // storage.remove('token')
      // storage.remove('info')
      // store.commit('isLoginToken', '');
      // AppEvents.emit('loginStatus', 'login')
      return response;
    } else {
      // ElMessage.error(message)
      return response;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    return Promise.reject(new Error(message || "Error"));
  },
  (error: any) => {
    if (error.response.data) {
      const { code, message } = error.response.data;
      console.log(code, '++error++', message);
      // ElMessage.error(message)

      // token 过期,重新登录

    }
    return Promise.reject(error.message);
  }
);

// // 导出 axios 实例
// export default service;
export const GET = (url: any, params: any) =>
  service({
    url,
    params,
  })
    .then((res) => Promise.resolve(res.data))
    .catch((err) => {
      console.log(err)
      // ElMessage.error(err)
    });

export const POST = (url: any, data: any) =>
  service
    .post(url, data)
    .then((res) => Promise.resolve(res.data))
    .catch((err) => {
      console.log(err)
      // ElMessage.error(err)
    });

export const PUT = (url: any, data: any) =>
  service
    .put(url, data)
    .then((res) => Promise.resolve(res.data))
    .catch((err) => {
      console.log(err)
      // ElMessage.error(err)
    });

export const DELETE = (url: any) =>
  service
    .delete(url)
    .then((res) => Promise.resolve(res.data))
    .catch((err) => {
      console.log(err)
      // ElMessage.error(err)
    });
